<template>
  <div>
    <el-dialog v-model="dialogVisible" width="80%" align-center :close-on-click-modal="false" :show-close="false"
      :before-close="handleClose" destroy-on-close draggable>
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>参加会议{{ ruleForm.id ? '编辑' : '新增' }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close">
            <CircleCloseFilled color="#fff" />
          </el-icon>
        </div>
      </template>
      <el-form :model="ruleForm" :rules="rules" label-width="130px" ref="ruleFormRef">
        <!-- 基本信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>基本信息</BaseHead>
          <div class="p-[10px]">

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="参会人" prop="parterName">
                  <el-select v-model="ruleForm.parterName" :disabled="Cookies.get('role-key') == 'biz_kyry'" @change="selectAuthor
      " filterable remote reserve-keyword placeholder=" 请输入关键字检索" :remote-method="remoteMethod" :loading="loading">
                    <el-option v-for="item  in  options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议名称" prop="name">
                  <el-input placeholder="请输入会议名称" v-model="ruleForm.name" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议类型" prop="meetingTypeId">
                  <el-radio-group v-model="ruleForm.meetingTypeId">
                    <el-radio v-for="  item   in   hylxList  " :key="item.code" :value="item.code" :label="item.name"
                      size="large"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主办单位" prop="chargeUnit">
                  <el-input placeholder="请输入主办单位" v-model="ruleForm.chargeUnit" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议位置">
                  <el-radio-group v-model="ruleForm.meetingScope">
                    <el-radio value="1" label="国内" size="large"></el-radio>
                    <el-radio value="2" label="国外" size="large"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="参会日期" prop="meetingDate">
                  <el-date-picker v-model="ruleForm.meetingDate" type="date" format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属单位" prop="unitId">
                  <el-select v-model="ruleForm.unitId" :disabled="Cookies.get('role-key') == 'biz_kyry'"
                    placeholder="请选择所属单位" clearable>
                    <el-option v-for="  item   in   zcgsdwList  " :key="item.codeColumn" :label="item.valueColumn"
                      :value="item.codeColumn" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="参会地址">
                  <el-input placeholder="请输入参会地址" v-model="ruleForm.meetingAddress" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="提交论文篇数">
                  <el-input placeholder="" v-model="ruleForm.paperNum" @input="handleInput" clearable>
                    <template #append>篇</template></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="特邀报告篇数">
                  <el-input placeholder="" v-model="ruleForm.reportNum" @input="handleInput1" clearable>
                    <template #append>篇</template></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="论文题目">
                  <el-input v-model="ruleForm.paperName" type="textarea" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="报告题目">
                  <el-input v-model="ruleForm.reportName" type="textarea" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="会议简介">
                  <el-input v-model="ruleForm.intro" type="textarea" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="会议相关文档">
                  <FileUpload :uploadUrl="uploadUrl" :limit="1" tip="最多可上传1个附件,每个附件大小不超过20M" v-model="fileList"
                    @change="fileChange">
                  </FileUpload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="submitForm(ruleFormRef, '-1')" v-if="ruleForm.checkstatus != '2'"
              :loading="btnLoading">暂存</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="checkEditButton()" :loading="btnLoading">{{
      Cookies.get("role-key") ==
        'biz_kyry' ? '提交' : ruleForm.checkstatus == '2' ? '保存' :
        '保存并通过' }}</el-button>
            <el-button type="primary" @click="initData()">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import FileUpload from "@/views/achievement/components/FileUpload.vue"
import { getjoinMeetingAdd, getjoinMeetingUpdate } from "@/api/achievement/xsjl"
import { getPersonDetails } from "@/api/achievement/common.js"
import { ElMessage, ElMessageBox } from "element-plus";
import Cookies from 'js-cookie'
import useUserStore from "@/store/modules/user";

const dialogVisible = defineModel();
const props = defineProps({
  hylxList: Array,
  zcgsdwList: Array,
})
const ruleForm = reactive({
  name: '',
  meetingTypeId: '',
  chargeUnit: '',
  meetingScope: '1',
  meetingDate: '',
  unitId: '',
  meetingAddress: '',
  paperName: '',
  reportName: '',
  intro: '',
  paperNum: null,
  reportNum: null,
  fileIds: '',
  parterName: '',
  parterId: '',
})
const rules = reactive({
  name: [
    { required: true, message: '请输入会议名称', trigger: 'blur' },
  ],
  parterName: [
    { required: true, message: '请输入参会人', trigger: 'blur' },
  ],
  chargeUnit: [
    { required: true, message: '请输入主办单位', trigger: 'blur' },
  ],
  meetingTypeId: [
    {
      required: true,
      message: '请选择会议类型',
      trigger: 'change',
    },
  ],
  unitId: [
    {
      required: true,
      message: '请选择所属单位',
      trigger: 'change',
    },
  ],
  meetingDate: [
    {
      required: true,
      message: '请选择参会日期',
      trigger: 'change',
    },
  ],
})

const btnLoading = ref(false)

const ruleFormRef = ref()
const submitForm = async (formEl, i) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      btnLoading.value = true;
      let params = {
        ...ruleForm,
      }
      params.submitType = i ? i : Cookies.get("role-key") == 'biz_kyry' ? '1' : '2'
      // if (i == '-1') {
      //   if (!ruleForm.id || Cookies.get("role-key") == 'biz_kyry') {
      //   } else {
      //     params.submitType = params.checkstatus
      //   }
      // }
      console.log(params, 'params')
      if (params.id) {
        getjoinMeetingUpdate(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            initData()
            emit('callBack', "")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      } else {
        getjoinMeetingAdd(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            initData()
            emit('callBack', "")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleInput = (value) => {
  if (!/^[1-9]\d*$/.test(value)) { // 正则表达式验证正整数
    ElMessage.error('请输入正整数');
    ruleForm.paperNum = null // 移除最后一个非法字符，或者设置为空字符串也可以，看具体需求
  }
}
const handleInput1 = (value) => {
  if (!/^[1-9]\d*$/.test(value)) { // 正则表达式验证正整数
    ElMessage.error('请输入正整数');
    ruleForm.reportNum = null // 移除最后一个非法字符，或者设置为空字符串也可以，看具体需求
  }
}

const options = ref([])
const loading = ref(false)
const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    let pamrs = {
      name: query
    }
    getPersonDetails(pamrs).then(res => {
      if (res.code == 200) {
        let arr = res.data;
        arr.map(item => {
          item.value = item.name + ' ' + item.account + ' ' + item.unitName;
          item.label = item.name + ' ' + item.account + ' ' + item.unitName;
        })
        options.value = arr
        loading.value = false
      }
    })
  } else {
    options.value = []
  }
}
// unit_id
const selectAuthor = (e, index, row) => {
  let userInfo = options.value.find(item => item.value == e)
  ruleForm.parterId = userInfo.id
  ruleForm.parterName = userInfo.name
}

const emit = defineEmits(['callBack']);
const handleClose = (done) => {
  Object.assign(ruleForm, {
    name: '',
    meetingTypeId: '',
    chargeUnit: '',
    meetingScope: '1',
    meetingDate: '',
    unitId: '',
    meetingAddress: '',
    paperName: '',
    reportName: '',
    intro: '',
    paperNum: null,
    reportNum: null,
    fileIds: '',
    parterName: '',
    parterId: '',
  })
  fileList.value = []
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  emit('callBack', "")
  done()
}
const initData = () => {
  Object.assign(ruleForm, {
    name: '',
    meetingTypeId: '',
    chargeUnit: '',
    meetingScope: '1',
    meetingDate: '',
    unitId: '',
    meetingAddress: '',
    paperName: '',
    reportName: '',
    intro: '',
    paperNum: null,
    reportNum: null,
    fileIds: '',
    parterName: '',
    parterId: '',
  })
  fileList.value = []
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  dialogVisible.value = false
}
const getRuleForm = (i) => {
  for (const key in i) {
    ruleForm[key] = i[key];
  }
  fileList.value = i.fileList.map((item) => {
    return {
      name: item.fileName,
      id: item.id,
    };
  });
  console.log(ruleForm, 'ruleForm')
}
const uploadUrl = `/commonFile/uploadFile?modelName=joinMeetingApply`;
const fileList = ref([]);
//上传的文件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  ruleForm.fileIds = ids.join(",");
};

const checkEditButton = () => {
  if (ruleForm.id) {
    if (Cookies.get("role-key") == 'biz_kyry') {
      return true
    } else if (Cookies.get("role-key") == 'biz_kyms') {
      if (ruleForm.checkstatus == '1' && ruleForm.isAuditor) {
        return true
      } else {
        return false
      }
    } else if (Cookies.get("role-key") == 'biz_kycgly') {
      if (ruleForm.checkstatus == '1') {
        return ruleForm.isAuditor ? true : false
      } else {
        return true
      }
    } else {
      return false
    }

  } else {
    return true
  }
}

const userStore = useUserStore();

const getKyryInfo = () => {
  if (Cookies.get("role-key") == 'biz_kyry') {
    let pamrs = {
      account: userStore.account
    }
    let kyryInfoArr = []
    getPersonDetails(pamrs).then(res => {
      if (res.code == 200) {
        kyryInfoArr = res.data.filter((item) => {
          return item.name == userStore.nickName
        });
        if (kyryInfoArr && kyryInfoArr.length) {
          ruleForm.parterName = kyryInfoArr[0].name
          ruleForm.parterId = kyryInfoArr[0].id
          ruleForm.unitId = kyryInfoArr[0].unitId
        }
      }
    })
  }
}



defineExpose({
  getRuleForm,
  getKyryInfo
})
</script>

<style scoped lang="scss">
@import url("@/views/achievement/index.scss");
</style>
